package com.gentics.labs.lh;

import java.util.List;
import java.util.Vector;

import com.gentics.api.portalnode.action.PluggableActionInvoker;
import com.gentics.api.portalnode.action.PluggableActionRequest;
import com.gentics.api.portalnode.action.PluggableActionResponse;

/**
 * helper to search for google hosted projects. requires Gentics Portal.Node 4+
 * runtime libraries.
 * 
 * @author laurin
 * 
 */
public class GoogleCodeLister {

	private final static String QUERYBASEURL = "http://code.google.com/hosting/search?filter=0&q=";
	private final static String QUERYKEYWORD = "gentics";

	// rss feed urls syntax:
	// http://code.google.com/feeds/p/XXX/updates/basic

	/**
	 * development method to easily view the result of the query, by printing
	 * them to stdout.
	 * 
	 * @param args
	 *            no arguments required
	 */
	public static void main(String[] args) {
		System.out.println(getProjectLinks());
	}

	/**
	 * get a list of links of google code hosted projects found when searching
	 * for gentics. does not support paging yet, so only first x results are
	 * returned.
	 * 
	 * @return the list of absolute html links, null when an error occurs, empty
	 *         list when nothing was found
	 */
	public static List<String> getProjectLinks() {

		PluggableActionRequest request = PluggableActionInvoker
				.createRequestObject();
		request.setParameter("url", QUERYBASEURL + QUERYKEYWORD);
		PluggableActionResponse response = PluggableActionInvoker
				.createResponseObject();

		boolean ok = PluggableActionInvoker.invokeAction("URLLoaderAction",
				request, response);
		String content = (String) response.getParameter("content");

		if (!ok) {
			return null;
		}

		boolean more = true;
		int start = 0;
		int tagend = 0;
		String tag = "";
		String url = "";
		String label = "";
		List<String> links = new Vector<String>();
		while (more) {
			// look for another tag
			int nextpos = content.indexOf("<a onmousedown", start);
			// found
			if (nextpos > -1) {
				// extract tag
				tagend = content.indexOf("</a>", nextpos);
				tag = content.substring(nextpos, tagend);

				url = tag.substring(tag.indexOf("href=\"") + 6, tag
						.indexOf("\">"));
				label = tag.substring(tag.indexOf("\">") + 2);

				links.add("<a href=\"http://code.google.com" + url + "\">"
						+ label + "</a>");

				// jump to next tag
				start = nextpos + 1;

			} else {
				more = false;
			}

		}

		return links;

	}

}
